package com.badibadi.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.badibadi.activity.InformActivity;
import com.badibadi.infos.AtModel;
import com.badibadi.infos.DiscussInfo;
import com.badibadi.infos.Results;
import com.badibadi.mytools.CalendarTools;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.DisplayUtil;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.test.pic.TestActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.sax.StartElementListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
/**
 * 这是评论的适配器
 * @author Administrator
 *
 */
public class PinLunAdapter extends BaseAdapter{
	
	private String TAG="PinLunAdapter";
	private List<DiscussInfo> mlist;
	private List<ij> panduan;//用于判断是评论还是回复
	private DisplayImageOptions options;
//	private int num=0;
	private Context context;
	
	private PinLunInterface pinLunInterface;//刷新接口
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(context);
				try {
					Utils.showMessage(context, "网络连接失败");
				} catch (Exception e){
				} 
				break;
			case 2:
				Utils.ExitPrgress(context);
				try {
					Utils.showMessage(context, "删除成功");
					if(pinLunInterface!=null)
					{
						pinLunInterface.DeletePingLunRefresh();
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 3:
				Utils.ExitPrgress(context);
				try {
					Utils.showMessage(context, "系统出错");
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 4://删除失败
				Utils.ExitPrgress(context);
				try {
					Utils.showMessage(context, "你没有权限做此操作");
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			
			default:
				break;
			}
		}
	};
	public PinLunAdapter(Context ct,List<DiscussInfo> list)
	{
		options = new DisplayImageOptions.Builder()
		.showStubImage(R.drawable.ic_stub)
		.showImageForEmptyUri(R.drawable.noimage)
		.showImageOnFail(R.drawable.noimage).cacheInMemory()
		.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5)).build();
		context=ct;
		mlist=list;
		panduan=new ArrayList<ij>();
//		num=num+mlist.size();
		
		for(int i=0;i<mlist.size();i++)
		{
			ij m=new ij();
		   m.i=i;
		   m.j=0;
//		      
			panduan.add(m);
			if(mlist.get(i).getTwo()!=null)
			{
				//统计数量
//				num=num+(mlist.get(i).getTwo().size());
				for(int j=0;j<mlist.get(i).getTwo().size();j++)
				{
					ij m1=new ij();
					m1.i=i;
					m1.j=j+1;
					panduan.add(m1);
//					     
				}
			}
		}
		
		
	}
	
	@Override
	public int getItemViewType(int position) {
		// TODO Auto-generated method stub
	
		if(panduan.get(position).j==0)
		{
			return 0;
		}else
			if(panduan.get(position).j!=0)
			{
				return 1;
			}
		
		return 0;
	}
	@Override
	public int getViewTypeCount() {
		// TODO Auto-generated method stub
		return 3;
	}
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return panduan.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		LayoutInflater inflater=LayoutInflater.from(context);
		int type=getItemViewType(position);
		ViewHolder holder=new ViewHolder();
		if(convertView==null)
		{
			if(type==0)
			{
				convertView=inflater.inflate(R.layout.pinglun_0, null);
			    holder.head=(ImageView)convertView.findViewById(R.id.head);
			    holder.message=(TextView)convertView.findViewById(R.id.message);
			    holder.nickName=(TextView)convertView.findViewById(R.id.nickName);
			    holder.post_time=(TextView)convertView.findViewById(R.id.post_time);
			    holder.set=(ImageView)convertView.findViewById(R.id.set);
			}
			else if(type==1)
			{
				convertView=inflater.inflate(R.layout.pinglun_1, null);
				  holder.head=(ImageView)convertView.findViewById(R.id.head);
				    holder.message=(TextView)convertView.findViewById(R.id.message);
				    holder.nickName=(TextView)convertView.findViewById(R.id.nickName);
				    holder.post_time=(TextView)convertView.findViewById(R.id.post_time);
				    holder.set=(ImageView)convertView.findViewById(R.id.set);
				    holder.to_nickName=(TextView)convertView.findViewById(R.id.to_nickName);
			}	
			convertView.setTag(holder);
		}else
		{
			holder=(ViewHolder) convertView.getTag();
		}
		if(type==0)
		{
//			   
			int i=panduan.get(position).i;
			int j=panduan.get(position).j-1;
			holder.message.setText(""+mlist.get(i).getMessage());
			holder.nickName.setText(""+mlist.get(i).getUser().getNickName());
			
			
			String posttime=CalendarTools.getFormatTime(Double.parseDouble(mlist.get(i).getPost_time()+"000"), "yyyy.MM.dd HH.mm");
			holder.post_time.setText(""+posttime);
			try {
				ImageLoader.getInstance().displayImage(Constants.BadiDownImgUrl+"/"+mlist.get(i).getUser().getHead()+Constants.appPhoto4img, holder.head, options);
			} catch (Exception e) {
				// TODO: handle exception
			}
			setPopWindow(holder.set,Utils.getUid(context),mlist.get(i).getId(),true,i,j);
			
		}
		if(type==1)
		{
//			   
			int i=panduan.get(position).i;
			int j=panduan.get(position).j-1;
			holder.message.setText(""+mlist.get(i).getTwo().get(j).getMessage());
			holder.nickName.setText(""+mlist.get(i).getTwo().get(j).getUser().getNickName());
			String posttime=CalendarTools.getFormatTime(Double.parseDouble(mlist.get(i).getPost_time()+"000"), "yyyy.MM.dd HH.mm");
			holder.post_time.setText(""+posttime);
			holder.to_nickName.setText(""+mlist.get(i).getTwo().get(j).getTo_user().getNickName());
			try {
				ImageLoader.getInstance().displayImage(Constants.BadiDownImgUrl+"/"+mlist.get(i).getTwo().get(j).getUser().getHead()+Constants.appPhoto4img, holder.head, options);
			} catch (Exception e) {
				// TODO: handle exception
			}
			setPopWindow(holder.set,Utils.getUid(context),mlist.get(i).getTwo().get(j).getId(),false,i,j);
		}
		return convertView;
	}
	/**
	 * 回复，举报和删除
	 * @param v pop要显示在v下面
	 * @param uid ---(必需)操作删除的用户ID
	 * @param id     (必需)要删除的评论的ID
	 * @param isPinlun 要删除的是否是评论的消息，如果不是就是回复
	 * 
	 * @param i;用于判断是要取哪条数据
	 * @param j;用于判断是要取哪条数据
	 *
	 *
	 */
	private void setPopWindow(View v,final String uid,final String id,final boolean isPinlun,final int i,final int j)
	{
		View root=LayoutInflater.from(context).inflate(R.layout.popwindow0, null);
		final PopupWindow popup=new PopupWindow(root, DisplayUtil.dip2px(context, 50),  DisplayUtil.dip2px(context, 100));
	    //回复
		root.findViewById(R.id.huifu).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
		root.findViewById(R.id.jubao).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(isPinlun==true)//如果是评论
				{
					Intent intent=new Intent(context,InformActivity.class);
					intent.putExtra("bei_person_id", mlist.get(i).getUid());//被举报人的内容的所属用户ID;
					intent.putExtra("table", "discuss");
					intent.putExtra("bei_cid", "0");
					
					intent.putExtra("bei_neirong_id", mlist.get(i).getId());//内容id
					context.startActivity(intent);
				
					((Activity) context).overridePendingTransition(R.anim.slide_left, R.anim.slide_right);
				}else//如果是回复
				{
					Intent intent=new Intent(context,InformActivity.class);
					intent.putExtra("bei_person_id", mlist.get(i).getTwo().get(j).getUser().getId());//被举报人的内容的所属用户ID;
					intent.putExtra("table", "discuss");
					intent.putExtra("bei_cid", "0");
					intent.putExtra("bei_neirong_id", mlist.get(i).getTwo().get(j).getId());//内容id
					context.startActivity(intent);
				
					((Activity) context).overridePendingTransition(R.anim.slide_left, R.anim.slide_right);
				}
			
			}
		});
		//删除评论
		root.findViewById(R.id.shanchu).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				commonality/deleteDiscuss
				if(isPinlun==true)
				{
					deleteDiscuss(uid,id);
				}
				else//删除回复还没有这接口
				{
					
				}
				
			}
		});
		//
		popup.setBackgroundDrawable(new BitmapDrawable());
		popup.setFocusable(true);
		popup.setTouchable(true);
		popup.setOutsideTouchable(true);
		v.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				popup.showAsDropDown(v);
			}
		});
	}
//	commonality/deleteDiscuss
	//删除评论
	/*
     * 个人+俱乐部操作删除评论---》》
     * 调用该接口之前需要注意：个人时，仅有自己（自己发布的内容的评论）有该权限删除；俱乐部时，自己（自己发布的内容的评论）和管理员都有权限删除
     * post
     * @param $uid---(必需)操作删除的用户ID
     * @param $id,    //(必需)要删除的评论的ID
     */
	public void deleteDiscuss(final String uid,final String id)
	{
//		deleteDiscuss
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				List<AtModel> list = new ArrayList<AtModel>();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", uid);
				map.put("id", id);
				String invite_content = Utils.sendRequest(map,
						Constants.BadiUrl_1 + "commonality/deleteDiscuss");
//				   
				if (invite_content != null) {
					Results results = Utils.checkResult_NNN(context,
							invite_content);
					if (results != null && !results.getRetmsg().equals("null")) {
//						   ("解析出来的数据:" + results.getRetmsg());
						try {
//							sd
							if(results.isRet()==true)
							handler.sendEmptyMessage(2);
							else
							handler.sendEmptyMessage(4);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}

			}
		});
		
		
	}
	
	
	
	class ij{
		public int i;//第几组
		public int j;//第i组的j-1列
		@Override
		public String toString() {
			return "ij [i=" + i + ", j=" + j + "]";
		}
		
	}
	static class ViewHolder{
		//第一种情况 评论
		public ImageView head;
		public TextView nickName;
		public TextView message;
		public TextView post_time;
		public ImageView set;
		//第二种情况 回复
		public TextView to_nickName;
	}
	public void setOnRefreshPingLunInterface(PinLunInterface refresh)
	{
		pinLunInterface=refresh;
	}
	
	
	public interface PinLunInterface
	{
		void DeletePingLunRefresh();//删除评论后刷新
	}
	
	
}
